package com.zhaokuner.parentstarter.ctrladaptor.http;

import com.alibaba.fastjson.JSON;
import com.zhaokuner.parentstarter.common.ResultData;
import com.zhaokuner.parentstarter.ctrladaptor.CtrlAdaptorDomainProperties;
import com.zhaokuner.parentstarter.handler.HttpReqInfoUtil;
import com.zhaokuner.parentstarter.resultcode.SuperResultCodeUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

/**
 * <p>
 * Description:http请求
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author 赵希坤 zhaoxikun
 * @date 2021/2/11 17:06
 */
@Log4j2
public class CtrlAdapterHttpClient implements ICtrlAdapterHttpClient {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CtrlAdaptorDomainProperties ctrlAdaptorDomainProperties;


    @Override
    public Object execute(CtrlAdaptorReqEntryClientInfo clientInfo) {

        CtrlAdaptorDomainProperties.Domain domain = ctrlAdaptorDomainProperties.getDomain().get(clientInfo.getServiceName());
        if (null == domain || StringUtils.isBlank(domain.getUrl())) {
            return ResultData.error(SuperResultCodeUtil.URL_NOT_FOUND);
        }
        String url = domain.getUrl() + clientInfo.getCtrlAdaptorReqEntry().toUrl();
        HttpEntity<Object> requestEntity = null;
        //获取原有请求的相关数据，主要是sessionId、 Language、Accept-language、和Content-Type
        HttpHeaders headers = HttpReqInfoUtil.get().getHeaders();
        //链路访问 可以打印日志
        if (HttpMethod.POST.equals(clientInfo.getCtrlAdaptorReqEntry().getHttpMethod())) {
            headers.setContentType(MediaType.APPLICATION_JSON);
            requestEntity = new HttpEntity<>(clientInfo.getCtrlAdaptorReqEntry().getPostContent(), headers);
        }
        try {
            ResponseEntity<String> entity = restTemplate.exchange(url, clientInfo.getCtrlAdaptorReqEntry().getHttpMethod(),
                    requestEntity, String.class, clientInfo.getCtrlAdaptorReqEntry().getParams());

            if (HttpStatus.OK.equals(entity.getStatusCode())) {
                return JSON.parseObject(entity.getBody(), clientInfo.getReturnType());
            }
            log.info("restTemplate ResponseEntity:{}", entity);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return ResultData.error(SuperResultCodeUtil.BAD_REQUEST);
    }

}
